package main

import (
	"container/heap"
	"fmt"
)

// 在优先队列中管理的item

type Item struct {
	// item的值，任意取值
	value string
	// 队列中项目的优先级
	priority int
	// 堆中项目的参数。该参数是更新所需的，由heap.Interface方法维护
	index int
}

// PriorityQueue实现堆。接口并保存项目

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int {
	return len(pq)
}

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, 	item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n - 1]
	item.index = -1
	*pq = old[0:n-1]
	return item
}

func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

func main() {
	items := map[string]int{
		"banana":3, "apple":2, "pear":4,
	}

	pq := make(PriorityQueue, len(items))
	i := 0
	for value, priority := range items{
		pq[i] = &Item{
			value: value,
			priority: priority,
			index: i,
		}
		i++
	}
	heap.Init(&pq)

	item := &Item{
		value: "orange",
		priority: 1,
	}

	heap.Push(&pq, item)
	pq.update(item, item.value, 5)

	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%.2d:%s ", item.priority, item.value)
	}
}
